package com.dfqy.front;

import com.dfqy.pojo.Appoint;
import com.dfqy.pojo.User;
import com.dfqy.service.AppointService;
import com.dfqy.service.UserService;
import com.dfqy.vo.Result;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Author : atyushu
 * Package : com.dfqy.front
 * ClassName : AppointFrontController
 * Create : 2023/8/1 - 13:19
 * Version : v1.0
 * Description : The class of controller for Appoint.
 */

@Validated
@RestController
@Api(tags = "AppointFrontController", description = "服务预约")
@RequestMapping("front/appoint")
public class AppointFrontController {

    @Autowired
    private AppointService appointService;

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @InitBinder
    public void initBinder(WebDataBinder webDataBinder) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        simpleDateFormat.setLenient(false);
        webDataBinder.registerCustomEditor(Date.class, new CustomDateEditor(simpleDateFormat, true));
    }

    @ApiOperation("用户在线预约, (着重注意: 日期的处理, 后端接收的格式为<yyyy-MM-dd HH:mm>, 对应前端表单中 <input type='datetime-local'>, 然而此标签, 获取用户输入的日期后, 会将此格式中的空格解析为'T', 例如<2023-8-9T9:10>, 因此在提交传输前, 务必将此'T'截掉, 例如: data.jointime = document.getElementById('posttime').value.replace('T', ' ');  ), (着重注意: 在官网中, 此预约表单, 有两个下拉框字段, 即 服务类型 和 选择中心, 需要查看其对应的controller来获取值, 例如: 选择中心, 需要查看ShopController中, 获取所有门店名称的方法; 服务类型<也称症状类型>, 对应SymTypeController), (东方启音官网参考, 点击: 首页 --> 服务群体 --> 点击具体服务内容 --> 右侧预约图标; 直达地址: https://www.ostcn.com/order)")
    @PostMapping("insert")
    public Result insert(@RequestBody Appoint appoint, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token != null && redisTemplate.opsForValue().get(token) != null) {
            User user = (User) redisTemplate.opsForValue().get(token);
            user.setScore(user.getScore() + 10);
            userService.update(user);
            appoint.setUserid(user.getId());
            redisTemplate.opsForValue().set(token,user);
        }
        int insert = appointService.insert(appoint);
        return insert > 0 ? Result.success("预约成功") : Result.error("预约失败");
    }
}
